import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Switch, Input, Select, Button, message, InputNumber, Table, Col, Tooltip, Row, Alert } from 'antd'
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
import errorMessage from 'share/errorMessage'
import { setCreditModel } from "actions/credit-setting";
import menuRoute from 'routes/menuRoute'
import moment from 'moment'

class CreditModelSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      saving: false,
      loading: false,
      notValid: false,
      data: {
        creditRankList: []
      }
    };
    this.disabled = false;
  }

  onCancel = () => {
    this.props.close();
  };

  handleBack = () => {
    this.context.router.push(menuRoute.getRouteItem('credit-model').url)
  };

  componentWillMount(){
    const { creditModel } = this.props;
    this.disabled = moment(creditModel.startDate).utc().isBefore(moment());
    this.disabled = this.disabled && (creditModel.endDate ? moment(creditModel.endDate).utc().isAfter(moment()) : true);
    this.setState({ loading: true });
    Promise.all([
      creditModelService.getCreditValid(creditModel.id),// true失效 false有效
      creditModelService.getCreditRank(creditModel.id)
    ]).then(res => {
      let valueWillSet = this.props.form.getFieldsValue();
      Object.keys(valueWillSet).map(key => {
        valueWillSet[key] = res[1].data[key];
      });
      this.props.form.setFieldsValue(valueWillSet);
      let data = res[1].data;
      data.creditRankList = data.creditRankList.sort((a, b) => a.sequence > b.sequence || -1);
      this.setState({ data, loading: false, notValid: res[0].data })
    }).catch(e => {
      this.setState({ loading: false });
      if(e && e.length && e.length > 0)
        errorMessage(e[0].response);
      else
        errorMessage(e.response);
    });
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { data } = this.state;
        const { creditModel } = this.props;
        if(values.initScore > values.maxScore || values.initScore < values.minScore){
          message.error(messages('credit-setting.key57')/*初始分值未在分域内，请检查*/);
          return ;
        }
        let rankLength = data.creditRankList.length;
        if(rankLength > 0){
          //因为中间都是连续的，所以只需要判断最后一个的最低分和分值域的起始分是否相同即可
          if(data.creditRankList[rankLength - 1].lowestScore !== values.minScore){
            message.error(messages('credit-setting.key58')/*还有尚未配置的分域*/);
            return ;
          }
          for(let i = 0; i < rankLength; i++){
            if(data.creditRankList[i].lowestScore === data.creditRankList[i].highestScore){
              message.error(messages('credit-setting.key59')/*有级别的最低分等于最高分，请检查*/);
              return ;
            }
          }
        }
        let target = JSON.parse(JSON.stringify(data));
        this.setState({ saving: true });
        values.id = this.props.creditModel.id;
        creditModelService.saveCreditRank(Object.assign({}, target, values)).then(res => {
          let targetCreditModel = JSON.parse(JSON.stringify(creditModel));
          targetCreditModel.initScore = values.initScore;
          targetCreditModel.maxScore = values.maxScore;
          targetCreditModel.minScore = values.minScore;
          targetCreditModel.rankFlag = values.rankFlag;
          this.props.dispatch(setCreditModel(targetCreditModel));
          this.props.onSave();
          this.setState({ saving: false });
          message.success(messages('credit-setting.key45')/*保存成功*/);
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ saving: false });
        })
      }
    });
  };

  handleChangeEnabled = checked => {
    const { data } = this.state;
    checked && data.creditRankList.length === 0 && this.handleNew();
    if(!checked){
      data.creditRankList = [];
      this.setState({ data });
    }
  };

  renderColumns = (record, key, index) => {
    const { data } = this.state;
    let creditRankList = data.creditRankList;
    const { getFieldValue } = this.props.form;
    switch(key){
      case 'highestScore':
        return <InputNumber value={record[key]}
                            style={{ width: 84 }}
                            precision={1}
                            disabled/>;
      case 'lowestScore':
        return <InputNumber onChange={value => this.handleChangeValue(value, key, index)}
                            value={record[key]}
                            style={{ width: 84 }}
                            precision={1}
                            max={record.highestScore}
                            min={(index === creditRankList.length - 1) ? getFieldValue('minScore') : creditRankList[index + 1].lowestScore}/>;
      case 'rankComment':
        return <Tooltip
          trigger={['focus']}
          title={record[key]}
          placement="topLeft"
          overlayStyle={{ width: 300 }}
        >
          <Input onChange={e => this.handleChangeValue(e.target.value, key, index)}
                 value={record[key]}
                 maxLength="500"/>
        </Tooltip>;
      case 'operate':
        return index === creditRankList.length - 1 && (
          <span>
            <a onClick={this.handleNew}>{messages('common.add')/*添加*/}</a>
            {index !== 0 && [
              <span className="ant-divider" key="divide"/>,
              <a key="delete" onClick={this.handleDelete}>{messages('common.delete')/*删除*/}</a>
            ] }
          </span>
        )
    }
  };

  handleChangeScore = (value, key) => {
    const { data } = this.state;
    let listLength = data.creditRankList.length;
    if(listLength > 0){
      if(listLength > 1){
        let nextMax = data.creditRankList[0].lowestScore;
        let nextMin = data.creditRankList[listLength - 1].highestScore;
        if((key === 'highestScore' && value < nextMax) || (key === 'lowestScore' && value > nextMin)){
          data.creditRankList = [{
            sequence: 1,
            rankName: 'A',
            highestScore: data.creditRankList[0].highestScore,
            lowestScore: data.creditRankList[listLength - 1].lowestScore,
            rankComment: ''
          }];
          data.creditRankList[0][key] = value;
        } else {
          if(key === 'highestScore')
            data.creditRankList[0][key] = value;
          else
            data.creditRankList[listLength - 1][key] = value;
        }
      }
      this.setState({ data });
    }
  };

  handleChangeValue = (value, key, index) => {
    const { data } = this.state;
    //如果是最小值，必须有值且如果有下一条的话必须比下一条的最小值高
    if(key === 'lowestScore'){
      if(!value && value !== 0){
        return ;
      }
      if(index !== data.creditRankList.length - 1 && value < data.creditRankList[index + 1].lowestScore){
        return ;
      }
    }
    data.creditRankList[index][key] = value;
    if(key === 'lowestScore' && index !== data.creditRankList.length - 1){
      data.creditRankList[index + 1].highestScore = value;
    }
    this.setState({ data });
  };

  handleDelete = () => {
    const { data } = this.state;
    data.creditRankList.pop();
    this.setState({ data })
  };

  handleNew = () => {
    const { getFieldValue } = this.props.form;
    const { data } = this.state;
    let sourceLength = data.creditRankList.length;
    let rankName = String.fromCharCode('A'.charCodeAt(0) + sourceLength);
    let nextMax = sourceLength === 0 ? getFieldValue('maxScore') : data.creditRankList[sourceLength - 1].lowestScore;
    if(nextMax === getFieldValue('minScore')){
      message.error(messages('credit-setting.key60')/*最低分已为信用分值域最低分，无法继续添加。*/);
      return ;
    }
    data.creditRankList.push({
      sequence: sourceLength + 1,
      rankName,
      highestScore: nextMax,
      lowestScore: getFieldValue('minScore'),
      rankComment: ''
    });
    this.setState({ data })
  };

  render(){
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { saving, data, notValid } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 15, offset: 1 },
    };
    const formsValue = getFieldsValue();
    return (
      <div>
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('credit-setting.key61')/*初始分值*/}>
            <Row gutter={10}>
              <Col span={10}>
                {getFieldDecorator('initScore', {
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.enter')  //请输入
                    }]
                })(
                  <InputNumber placeholder={messages('common.please.enter')/*请输入*/} precision={1} disabled={this.disabled}/>
                )}
              </Col>
              <Col span={14}>
                <Alert message={messages('credit-setting.key105')/*生效后，不可再修改初始分值；若发生变动，系统将对所有应用公司进行重新初始化。*/} type="info" showIcon />
              </Col>
            </Row>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key98')/*信用分值域*/} required>
            <Row gutter={10}>
              <Col span={10}>
                <Row>
                  <Col span={9}>
                    <FormItem>
                      {getFieldDecorator('minScore', {
                        rules: [
                          {
                            required: true,
                            message: messages('common.please.enter')  //请输入
                          }]
                      })(
                        <InputNumber placeholder={messages('common.please.enter')/*请输入*/}
                                     precision={1}
                                     disabled={this.disabled}
                                     onChange={value => this.handleChangeScore(value, 'lowestScore')}/>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem>
                      <span style={{ marginRight: 10 }}>{messages('credit-setting.key99')/*至*/}</span>
                      {getFieldDecorator('maxScore', {
                        rules: [
                          {
                            required: true,
                            message: messages('common.please.enter')  //请输入
                          }]
                      })(
                        <InputNumber placeholder={messages('common.please.enter')/*请输入*/}
                                     precision={1}
                                     disabled={this.disabled}
                                     onChange={value => this.handleChangeScore(value, 'highestScore')}/>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
              <Col span={14}>
                <Alert message={messages('credit-setting.key106')/*设置记分的上下限，防止出现超出范围的分；若发生变动，系统将对所有应用公司进行重新初始化。*/} type="info" showIcon />
              </Col>
            </Row>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key64')/*信用分级*/}>
            <Row gutter={10}>
              <Col span={10}>
                {getFieldDecorator('rankFlag', {
                  valuePropName: 'checked'
                })(
                  <Switch onChange={this.handleChangeEnabled}
                          disabled={formsValue.maxScore === null || formsValue.maxScore === '' || formsValue.minScore === null || formsValue.minScore === ''}/>
                )}
              </Col>
              <Col span={14}>
                <Alert message={messages('credit-setting.key65')/*下方最高等级的最高分为包含，其余为不包含。*/} type="info" showIcon />
              </Col>
            </Row>
          </FormItem>
          {formsValue.rankFlag && (
            <FormItem {...formItemLayout} label={messages('credit-setting.key66')/*分级设置*/}>
              <Table columns={[
                                {title: messages('common.sequence')/*序号*/, dataIndex: 'sequence', width: 48},
                                {title: messages('credit-setting.key67')/*级别*/, dataIndex: 'rankName', width: 48},
                                {title: messages('credit-setting.key68')/*最低分*/, dataIndex: 'lowestScore', render: (text, record, index) => this.renderColumns(record, 'lowestScore', index), width: 100},
                                {title: messages('credit-setting.key69')/*最高分*/, dataIndex: 'highestScore', render: (text, record, index) => this.renderColumns(record, 'highestScore', index), width: 100},
                                {title: messages('credit-setting.key70')/*等级描述*/, dataIndex: 'rankComment', render: (text, record, index) => this.renderColumns(record, 'rankComment', index)},
                                {title: messages('common.operation')/*操作*/, dataIndex: 'operate', render: (text, record, index) => this.renderColumns(record, 'operate', index), width: 100}
                              ]}
                     bordered
                     pagination={false}
                     rowKey="sequence"
                     dataSource={data.creditRankList}
                     size="middle"/>
            </FormItem>
          )}
          <FormItem wrapperCol={{ offset: 7 }}>
            <Button type="primary" htmlType="submit" loading={saving} disabled={notValid}>{messages('common.save')/* 保存 */}</Button>
            <Button style={{ marginLeft: 10 }} onClick={this.handleBack}>{messages('common.back')/*返回*/}</Button>
          </FormItem>
        </Form>
      </div>
    )
  }

}

CreditModelSetting.propTypes = {
  onSave: React.PropTypes.func,
};

CreditModelSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    creditModel: state.creditSetting.creditModel,
  }
}
const WrappedCreditModelSetting = Form.create()(CreditModelSetting);

export default connect(mapStateToProps)(WrappedCreditModelSetting);
